<template>
  <view class="search-container">
    <!-- 固定顶部区域 -->
    <view class="fixed-header" :style="{paddingTop: statusBarHeight + 'px'}">
      <!-- 顶部导航 -->
      <view class="header">
        <view class="back-button" @click="goBack">
          <image class="back-icon" src="/static/back.png"></image>
        </view>
        <text class="page-title">岗位/公司</text>
      </view>
      
      <!-- 搜索框 -->
      <view class="search-bar-wrap">
        <view class="search-bar">
          <image class="search-icon" src="/static/search.1 1@1.5x.png" mode="aspectFit" />
          <input
            class="search-input"
            v-model="keyword"
            placeholder="小红书"
            :focus="true"
            confirm-type="search"
            @confirm="doSearch"
            @input="onInput"
          />
        </view>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="main-content" :style="{marginTop: (180 + statusBarHeight) + 'rpx'}">
      <!-- 搜索结果 -->
      <view v-if="searched" class="search-result-section">
        <!-- 结果选项卡 -->
        <view class="result-tabs">
          <text :class="{tab:true,active:activeTab==='job'}" @click="activeTab='job'">岗位</text>
          <text :class="{tab:true,active:activeTab==='company'}" @click="activeTab='company'">名企</text>
        </view>

        <!-- 搜索结果列表 -->
        <scroll-view scroll-y="true" class="result-list">
          <!-- Job cards -->
          <view v-if="activeTab==='job'" class="list-content">
            <view v-for="job in searchJobs" :key="job.id" class="job-card" @click="goJob(job.id)">
              <view class="job-title-row">
                <text class="job-title">{{ job.title }}</text>
                <text class="job-salary">{{ job.salary }}</text>
              </view>
              <view class="job-company-row">
                <text class="company">{{ job.company }}</text>
                <text class="tag" v-for="(tag, i) in job.tags" :key="i">{{ tag }}</text>
              </view>
            </view>
            <view v-if="!searchJobs.length" class="empty-result">暂无相关岗位</view>
          </view>
          <!-- Company cards -->
          <view v-else class="list-content">
            <view v-for="comp in searchCompanies" :key="comp.id" class="company-card" @click="goCompany(comp.id)">
              <text class="company-name">{{ comp.company }}</text>
              <text class="company-info">{{ comp.type }}</text>
            </view>
            <view v-if="!searchCompanies.length" class="empty-result">暂无相关公司</view>
          </view>
        </scroll-view>
      </view>

      <!-- 默认内容（历史搜索和猜你想搜） -->
      <view v-else class="default-content">
        <!-- 历史搜索 -->
        <view v-if="historyList.length > 0" class="section-block">
          <text class="section-title">历史搜索</text>
          <view class="hot-tags">
            <view
              v-for="(item, index) in historyList.slice(0, 7)"
              :key="index"
              class="tag"
              @click="selectTag(item)"
            >{{ item }}</view>
          </view>
        </view>

        <!-- 猜你想搜 -->
        <view class="section-block">
          <text class="section-title">猜你想搜</text>
          <view class="hot-tags">
            <view
              v-for="tag in hotTags"
              :key="tag"
              class="tag"
              @click="selectTag(tag)"
            >{{ tag }}</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      keyword: '',
      historyList: uni.getStorageSync('searchHistory') || [],
      hotTags: ['Designer', 'Administrate', 'NGO', 'Manager', 'Management', 'IT', 'Marketing', 'Developer', 'SEO'],
      searched: false,
      activeTab: 'job',
      searchJobs: [],
      searchCompanies: [],
      // mock job data
      allJobs: [
        {
          id: 'job1',
          title: '用户产品经理',
          company: '小红书',
          salary: '18-42k*16',
          tags: ['互联网', '产品'],
          companyId: 'company1',
          date: '2025-4',
          location: '北京',
          views: 450,
          recruitType: '校园招聘'
        },
        {
          id: 'job2',
          title: '前端开发工程师',
          company: '小红书',
          salary: '25-45k*16',
          tags: ['React', 'Node'],
          companyId: 'company1',
          date: '2025-4',
          location: '上海',
          views: 380,
          recruitType: '社会招聘'
        },
        {
          id: 'job3',
          title: 'Java后端开发',
          company: '阿里巴巴',
          salary: '22-45k*16',
          tags: ['Java', '微服务'],
          companyId: 'company2',
          date: '2025-4',
          location: '杭州',
          views: 520,
          recruitType: '事业编制'
        },
        {
          id: 'job4',
          title: '产品运营实习生',
          company: '字节跳动',
          salary: '4k-8k',
          tags: ['运营', '实习'],
          companyId: 'company3',
          date: '2025-4',
          location: '深圳',
          views: 280,
          recruitType: '校园实习'
        },
        {
          id: 'job5',
          title: '周末课程助教',
          company: '好未来',
          salary: '200/天',
          tags: ['教育', '兼职'],
          companyId: 'company4',
          date: '2025-4',
          location: '广州',
          views: 180,
          recruitType: '热门兼职'
        }
      ],
      allCompanies: [
        { id: 'company1', company: '小红书', type: '生活方式平台' },
        { id: 'company2', company: '阿里巴巴', type: '互联网公司' },
        { id: 'company3', company: '字节跳动', type: '互联网公司' },
        { id: 'company4', company: '好未来', type: '教育培训' }
      ],
      statusBarHeight: 0,
      isLoading: false,
      debounceTimer: null
    }
  },
  onLoad(){
    const sys = uni.getSystemInfoSync();
    this.statusBarHeight = sys.statusBarHeight || (sys.safeAreaInsets && sys.safeAreaInsets.top) || 0;
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    // 联想搜索
    async onInput() {
      if (this.debounceTimer) clearTimeout(this.debounceTimer);
      
      if (!this.keyword.trim()) {
        this.searched = false;
        this.searchJobs = [];
        this.searchCompanies = [];
        return;
      }

      // 模拟搜索结果
      this.debounceTimer = setTimeout(() => {
        const kw = this.keyword.toLowerCase();
        // 同时搜索岗位和公司
        this.searchJobs = this.allJobs.filter(j =>
          j.title.toLowerCase().includes(kw) || 
          j.company.toLowerCase().includes(kw) ||
          j.recruitType.toLowerCase().includes(kw)
        );
        this.searchCompanies = this.allCompanies.filter(c =>
          c.company.toLowerCase().includes(kw)
        );
        this.searched = true;
      }, 300);
    },

    // 执行搜索（点击搜索按钮或回车时）
    async doSearch() {
      if (!this.keyword.trim()) return;
      
      this.isLoading = true;
      try {
        const res = await uni.request({
          url: 'https://api.example.com/v1/search',
          method: 'GET',
          data: {
            keyword: this.keyword,
            type: this.activeTab,
            page: 1,
            pageSize: 20
          }
        });

        if (res[1].statusCode === 200 && res[1].data) {
          if (this.activeTab === 'job') {
            this.searchJobs = res[1].data.jobs || [];
          } else {
            this.searchCompanies = res[1].data.companies || [];
          }
          this.searched = true;

          // 保存搜索历史
          const index = this.historyList.indexOf(this.keyword);
          if (index > -1) {
            this.historyList.splice(index, 1);
          }
          this.historyList.unshift(this.keyword);
          if (this.historyList.length > 7) {
            this.historyList = this.historyList.slice(0, 7);
          }
          uni.setStorageSync('searchHistory', this.historyList);
        }
      } catch (error) {
        console.error('搜索失败:', error);
      } finally {
        this.isLoading = false;
      }
    },
    selectTag(tag) {
      this.keyword = tag;
      // 触发联想搜索
      if (this.keyword.trim()) {
        // 模拟搜索：过滤本地数组
        const kw = this.keyword.toLowerCase();
        this.searchJobs = this.allJobs.filter(j=>
          j.title.toLowerCase().includes(kw) || j.company.toLowerCase().includes(kw)
        );
        this.searchCompanies = this.allCompanies.filter(c=>c.company.toLowerCase().includes(kw));
        this.searched = true;
      } else {
        // 输入框为空时，清空搜索结果
        this.searched = false;
        this.searchJobs = [];
        this.searchCompanies = [];
      }

      // 如果是新的搜索词，保存到历史记录
      const index = this.historyList.indexOf(tag);
      if (index > -1) {
        // 如果已存在，先删除旧记录
        this.historyList.splice(index, 1);
      }
      // 添加到开头
      this.historyList.unshift(tag);
      // 限制最多7条
      if (this.historyList.length > 7) {
        this.historyList = this.historyList.slice(0, 7);
      }
      // 保存到本地存储
      uni.setStorageSync('searchHistory', this.historyList);
    },
    goJob(id){
      if(!id) return;
      uni.navigateTo({url:`/pages/job-detail/index?id=${id}`} );
    },
    goCompany(id){
      if(!id) return;
      uni.navigateTo({url:`/pages/company-detail/index?id=${id}`});
    }
  }
}
</script>

<style scoped>
.search-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: linear-gradient(
    180deg,
    #F0FDF8 0%,
    #E6FAF5 20%,
    #D0F0EE 50%,
    #E8F5E4 80%,
    #F8FBF8 95%,
    #FFFFFF 100%
  );
}

.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 50;
  background: transparent;
}

.header {
  position: relative;
  background: transparent;
  padding: 30rpx 36rpx 20rpx;
  color: #333333;
  display: flex;
  justify-content: center;
  align-items: center;
}

.back-button {
  position: absolute;
  top: 22rpx;
  left: 36rpx;
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(16, 185, 129, 0.15);
  backdrop-filter: blur(20rpx);
  border: 2rpx solid rgba(16, 185, 129, 0.2);
  box-shadow:
    0 8rpx 20rpx rgba(0, 0, 0, 0.15),
    inset 0 2rpx 4rpx rgba(255, 255, 255, 0.1);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
}

.back-button:active {
  transform: scale(0.9) translateY(2rpx);
  background: rgba(16, 185, 129, 0.25);
}

.back-icon {
  width: 36rpx;
  height: 36rpx;
  opacity: 0.8;
  transition: opacity 0.3s ease;
  filter: brightness(0);
}

.page-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #333333;
}

.search-bar-wrap {
  height: 80rpx;
  padding: 0 36rpx 20rpx 36rpx;
}

.search-bar {
  flex-direction: row;
  display: flex;
  align-items: center;
  background: #ffffff;
  border: 1rpx solid #e8e8e8;
  border-radius: 50rpx;
  height: 80rpx;
  padding: 0 24rpx;
  transition: all 0.3s ease;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.search-bar:focus-within {
  border-color: #05A273;
  box-shadow: 0 2rpx 12rpx rgba(5, 162, 115, 0.15);
}

.search-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 16rpx;
  opacity: 0.7;
}

.search-bar:focus-within .search-icon {
  opacity: 1;
}

.search-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 30rpx;
  color: #333;
  background: transparent;
}

.search-input::placeholder {
  color: #999;
}

.main-content {
  padding: 40rpx 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  width: 100%;
  overflow-x: hidden;
}

.search-result-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: transparent;
  overflow: hidden;
}

.result-tabs {
  flex-direction: row;
  display: flex;
  justify-content: center;
  gap: 20rpx;
  padding: 20rpx 0;
  background: transparent;
  border-bottom: 1rpx solid rgba(240, 240, 240, 0.3);
}

.tab {
  font-size: 30rpx;
  color: #666;
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  transition: all 0.3s ease;
}

.tab.active {
  color: #05A273;
  background: rgba(5, 162, 115, 0.1);
  font-weight: 600;
}

.result-list {
  flex: 1;
  height: calc(100vh - 300rpx);
  background: transparent;
}

.list-content {
  padding: 0 24rpx 40rpx;
}

.default-content {
  flex: 1;
  padding: 0rpx 32rpx;
  overflow-x: hidden;
  width: 100%;
  box-sizing: border-box;
}

.section-block {
  margin: 24rpx 0;
  width: 100%;
}

.section-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 600;
  margin-bottom: 16rpx;
  display: block;
}

.hot-tags {
  flex-direction: row;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: flex-start;
  gap: 10rpx;
  width: 100%;
  box-sizing: border-box;
  overflow: visible;
}

.tag {
  flex-direction: row;
  background: #ffffff;
  color: #666;
  font-size: 22rpx;
  border: 1rpx solid #e8e8e8;
  border-radius: 30rpx;
  padding: 8rpx 16rpx;
  transition: all 0.3s ease;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.04);
  white-space: nowrap;
  display: inline-flex;
  align-items: center;
  flex-shrink: 0;
  min-width: 0;
  max-width: 200rpx;
  box-sizing: border-box;
}

.tag:active {
  background: #f8f9fa;
  border-color: #05A273;
  transform: scale(0.98);
}

.job-card, .company-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16rpx;
  border: 1rpx solid rgba(240, 240, 240, 0.6);
  padding: 24rpx 20rpx;
  margin-bottom: 16rpx;
  transition: all 0.3s ease;
  backdrop-filter: blur(10rpx);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.job-card:active, .company-card:active {
  transform: scale(0.98);
  background: #f8f9fa;
}

.job-title-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12rpx;
}

.job-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
  flex: 1;
  margin-right: 16rpx;
}

.job-salary {
  color: #ff4757;
  font-size: 28rpx;
  font-weight: 600;
}

.job-company-row {
  flex-direction: row;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  justify-content: flex-start;
  gap: 8rpx;
}

.company {
  color: #666;
  font-size: 24rpx;
  margin-right: 12rpx;
}

.job-company-row .tag {
  font-size: 20rpx;
  padding: 4rpx 10rpx;
  background: #ffffff;
  color: #888;
  border: 1rpx solid #e8e8e8;
  border-radius: 20rpx;
  box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.04);
  white-space: nowrap;
  display: inline-flex;
  align-items: center;
  flex-shrink: 0;
}

.company-name {
  font-size: 30rpx;
  color: #333;
  font-weight: 600;
  display: block;
  margin-bottom: 8rpx;
}

.company-info {
  font-size: 24rpx;
  color: #666;
  display: block;
}

.empty-result {
  text-align: center;
  color: #999;
  font-size: 28rpx;
  padding: 60rpx 20rpx;
  background: rgba(248, 249, 250, 0.8);
  border-radius: 16rpx;
  margin: 20rpx 0;
  backdrop-filter: blur(10rpx);
  border: 1rpx solid rgba(240, 240, 240, 0.6);
}
</style> 